package com.sojson.config.mybatis.objecthandler;

import java.io.IOException;
import java.util.Date;

import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.sojson.enums.core.EDelFlagStatus;
import com.sojson.util.DateUtil;
import com.sojson.util.param.ParamUtil;
import com.sojson.util.servlet.ServletUtil;
import com.sojson.util.token.TokenUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * Mybatis自动填充
 * 
 * @author liu
 * @date 2022-01-20
 */
@Slf4j
@Component
public class CustomMetaObjectHandler implements MetaObjectHandler {

    public static final String CREATE_BY = "createBy";
    public static final String CREATE_TIME = "createTime";
    public static final String UPDATE_BY = "updateBy";
    public static final String UPDATE_TIME = "updateTime";
    public static final String DEL_FLAG = "delFlag";

    @Override
    public void insertFill(MetaObject metaObject) {
        Date nowDate = DateUtil.nowDate();
        String userId = null;
        try {
            if (ServletUtil.getHttpServletRequestNo() != null && ParamUtil.isLogin()) {
                userId = TokenUtil.getUserId();
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        this.strictInsertFill(metaObject, CREATE_BY, String.class, userId);
        this.strictInsertFill(metaObject, CREATE_TIME, Date.class, nowDate);
        this.strictInsertFill(metaObject, UPDATE_BY, String.class, userId);
        this.strictInsertFill(metaObject, UPDATE_TIME, Date.class, nowDate);
        this.strictInsertFill(metaObject, DEL_FLAG, Integer.class, EDelFlagStatus.NO.getCode());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Date nowDate = DateUtil.nowDate();
        String userId = null;
        try {
            if (ServletUtil.getHttpServletRequestNo() != null && ParamUtil.isLogin()) {
                userId = TokenUtil.getUserId();
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        this.strictUpdateFill(metaObject, UPDATE_BY, String.class, userId);
        this.strictUpdateFill(metaObject, UPDATE_TIME, Date.class, nowDate);
    }

}